<?php
/**
 * @Author: gan
 * @Description:RedisDriver redis存储
 * @File:  RedisDriver
 * @Version: 1.0.0
 * @Date: 2022/5/24 10:22 上午
 */
declare(strict_types=1);

namespace RX\Component\CloudPrint\Driver;

use Psr\SimpleCache\CacheInterface;
use RX\Component\Cache\RedisCache;

class RedisDriver implements CacheInterface
{
    protected string     $name;
    protected string     $prefix;

    public function __construct($name, $prefix)
    {
        $this->name   = $name ?: "default";
        $this->prefix = $prefix ?: 'cloud_print_cache:';
    }

    /**
     * @return string
     */
    protected function getPrefix(): string
    {
        return $this->prefix;
    }

    /**
     * 获取缓存的 key
     * @param string $key
     * @return string
     */
    public function getCacheKey(string $key)
    {
        return $this->getPrefix() . $key;
    }

    /**
     * 设置缓存
     * @param string $key
     * @param mixed $value
     * @param int $ttl
     * @return bool
     */
    public function set($key, $value, $ttl = 0)
    {
        return RedisCache::setName($this->name)->set($this->getCacheKey($key), $value, $ttl);
    }

    /**
     * 获取缓存
     * @param string $key
     * @param null $default
     * @return mixed|null
     * @throws \Exception
     */
    public function get($key, $default = null)
    {
        $result = RedisCache::setName($this->name)->get($this->getCacheKey($key));
        return $result ?: $default;
    }


    /**
     * 删除缓存
     * @param string $key
     * @return bool
     */
    public function delete($key)
    {
        return RedisCache::setName($this->name)->del($this->getCacheKey($key));
    }


    public function clear()
    {
    }


    public function getMultiple($keys, $default = null)
    {
    }


    public function setMultiple($values, $ttl = null)
    {
    }


    public function deleteMultiple($keys)
    {
    }

    /**
     * 缓存是否存在
     * @param string $key
     * @return bool
     */
    public function has($key)
    {
        return RedisCache::setName($this->name)->exists($this->getCacheKey($key));
    }
}
